package com.kaiwukj.android.ufamily.mvp.http.utils;

import com.kaiwukj.android.ufamily.mvp.http.api.ApiRespCode;
import com.kaiwukj.android.ufamily.mvp.http.entity.base.ApiResp;
import com.kaiwukj.android.ufamily.mvp.http.entity.base.ApiRespB2;
import com.kaiwukj.android.ufamily.mvp.http.exception.ApiException;
import com.kaiwukj.android.ufamily.mvp.http.exception.DataEmptyException;

import io.reactivex.FlowableTransformer;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class RxUtils {

    /**
     * 统一线程处理
     *
     * @param <T>
     * @return
     */
    public static <T> FlowableTransformer<T, T> rxSchedulerHelper() {    //compose简化线程
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> ObservableTransformer<T, T> schedulerHelper() {
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    //解析数据
    public static <T> ObservableTransformer<ApiResp<T>, T> handleResult() {
        return upstream -> upstream.map((Function<ApiResp<T>, T>) tApiResult -> {
            //LogUtils.d("result:"+ GsonUtils.toJson(tApiResult));
            int code = tApiResult.getCode();
            if (code != ApiRespCode.REQUEST_OK) {
                throw new ApiException(code, tApiResult.getMsg());
            }
           // if (tApiResult.getData() == null) throw new DataEmptyException();
            return tApiResult.getData();
        });
    }

    //解析返回码
    public static ObservableTransformer<ApiResp, Integer> handleCode() {
        return upstream -> upstream.map((Function<ApiResp, Integer>) apiResult -> {
            int code = apiResult.getCode();
            if (code != ApiRespCode.REQUEST_OK) {
                throw new ApiException(code, apiResult.getMsg());
            }
            return code;
        });
    }

    //解析数据
    public static <T> ObservableTransformer<ApiRespB2<T>, T> handleResultB2() {
        return upstream -> upstream.map((Function<ApiRespB2<T>, T>) tApiResult -> {
            //LogUtils.d("result:"+ GsonUtils.toJson(tApiResult));
            int code = Integer.parseInt(tApiResult.getErrno());
            if (code != 0) {
                throw new ApiException(code, tApiResult.getErrmsg());
            }
            return tApiResult.getData();
        });
    }

    //解析返回码
    public static ObservableTransformer<ApiRespB2, Integer> handleCodeB2() {
        return upstream -> upstream.map((Function<ApiRespB2, Integer>) apiResult -> {
            int code = Integer.parseInt(apiResult.getErrno());
            if (code != 0) {
                throw new ApiException(code, apiResult.getErrmsg());
            }
            return code;
        });
    }

}
